package com.example.movie.ui.cinema

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.example.movie.R
import com.example.movie.common.constants.AppConstants
import com.example.movie.common.model.vm.CommonViewModel
import com.example.movie.common.service.LocationService
import com.example.movie.data.cinema.model.bean.CinemaInfo
import com.example.movie.data.cinema.model.vm.CinemaViewModel
import com.example.movie.data.movie.factory.CinemaViewModelFactory
import com.example.movie.ui.cinema.adapter.CinemaItemAdapter
import com.example.movie.ui.cinema.adapter.ConstellationAdapter
import com.example.movie.ui.cinema.adapter.GirdDropDownAdapter
import com.example.movie.ui.cinema.adapter.ListDropDownAdapter
import com.youth.banner.BannerConfig
import com.youth.banner.Transformer
import com.youth.banner.loader.ImageLoaderInterface
import kotlinx.android.synthetic.main.fragment_cinema.*
import java.util.concurrent.TimeUnit


class CinemaFragment : Fragment() {

    private val cinemaViewModel: CinemaViewModel by viewModels(factoryProducer = { CinemaViewModelFactory() })
    private val commonViewModel: CommonViewModel by activityViewModels()

    private val headers = arrayOf("类型", "价格", "距离", "星级")
    private val popupViews = mutableListOf<View>()
    private var hallTypeAdapter: GirdDropDownAdapter? = null
    private var priceAdapter: ListDropDownAdapter? = null
    private var distanceAdapter: ListDropDownAdapter? = null
    private var starAdapter: ConstellationAdapter? = null
    private val hallType = mutableListOf<String>()
    private val price = arrayOf("不限", "由低到高", "由高到低")
    private val distance = arrayOf("不限", "远", "近")
    private val stars = mutableListOf(
        "不限",
        "一星级",
        "二星级",
        "三星级",
        "四星级",
        "五星级",
    )

    private lateinit var cityCode: String

    /**
     * 保存影厅类型数据和其对应的id
     */
    private val hallTypeMap = hashMapOf<Int, Int>()

    private var pricePosition: Int = 0
    private var starPosition = 0

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        setUpObserver()
        return inflater.inflate(R.layout.fragment_cinema, container, false)
    }

    private fun setUpObserver() {
        var selected = false
        commonViewModel.selectedCity.observe(viewLifecycleOwner, {
            it?.let {
                cityCode = commonViewModel.selectedCity.value!!.code
                cinemaViewModel.loadCinemaDataByHallType(cityCode, -1, pricePosition, starPosition)
                selected = true
            }
        })
        if (!selected) {
            LocationService.startLocation(requireContext(), commonViewModel)
            commonViewModel.locatedCity.observe(viewLifecycleOwner, {
                it?.let {
                    cityCode = commonViewModel.locatedCity.value!!.code
                    //default:guilin
                    cinemaViewModel.loadCinemaDataByHallType(
                        "101300501",
                        -1,
                        pricePosition,
                        starPosition
                    )
                    //定位成功即可关闭定位服务
                    LocationService.stopLocation()
                }
            })
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initBanner()
        initDropDownMenu(requireContext())
        initCinemasRecycleView()
    }

    private fun initBanner() {
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE)
        banner.setImageLoader(GlideImageLoader())
        banner.setImages(listOf(AppConstants.demoImage, AppConstants.demoImage))
        banner.setBannerAnimation(Transformer.BackgroundToForeground)
        banner.setBannerTitles(listOf("万达影院", "桂林影院"))
        banner.isAutoPlay(true)
        banner.setDelayTime(TimeUnit.SECONDS.toMillis(5).toInt())
        banner.setIndicatorGravity(BannerConfig.CENTER)
        banner.start()
    }

    /**
     * 加载影院信息
     */
    private fun initCinemasRecycleView() {
        cinema_list?.apply {
            this.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)

            commonViewModel.selectedCity.observe(viewLifecycleOwner, {
                cinemaViewModel.loadCinemaDataByHallType(it.code, -1, pricePosition, starPosition)
            })

            cinemaViewModel.cinemas.observe(viewLifecycleOwner, { it ->
                with(it.success) {
                    this?.agentList?.let {
                        val titles = mutableListOf<String>()
                        val images = mutableListOf<String>()
                        for (element in it) {
                            titles.add(element.agentName!!)
                            images.add(AppConstants.STATIC_SOURCE_URL + element.agentIcon)
                        }

                        if (titles.isNotEmpty()) {
                            banner.setBannerTitles(titles)
                            banner.setImages(images)
                            banner.start()
                        }

                        val cinemas = mutableListOf<CinemaInfo>()
                        repeat(it.size) { idx ->
                            it[idx].apply {
                                cinemas.add(
                                    CinemaInfo(
                                        agentId,
                                        agentName,
                                        lowestPrice,
                                        address,
                                        11.2f,
                                        arrayOf(this.carPark, this.glasses, this.children),
                                        null
                                    )
                                )
                            }
                        }
                        val baseAdapter = CinemaItemAdapter(cinemas,requireContext())
                        adapter = baseAdapter
                        baseAdapter.notifyDataSetChanged()
                    }
                    this?.hallTypeList?.let {
                        hallType.clear()
                        hallType.add("不限")
                        hallTypeMap[0] = -1
                        repeat(it.size) { idx ->
                            with(it[idx]) {
                                hallTypeId?.let { it1 -> hallTypeMap.put(idx + 1, it1) }
                                hallTypeName?.let { typeName -> hallType.add(typeName) }
                            }
                        }
                    }
                }
            })

        }

    }

    /**
     * 初始化多选择器
     */
    @SuppressLint("InflateParams")
    private fun initDropDownMenu(context: Context) {
        val hallTypeView = ListView(context)
        hallTypeAdapter =
            GirdDropDownAdapter(
                context,
                hallType
            )
        hallTypeView.dividerHeight = 0
        hallTypeView.adapter = hallTypeAdapter

        val priceView = ListView(context)
        priceView.dividerHeight = 0
        priceAdapter =
            ListDropDownAdapter(
                context,
                listOf(*price)
            )
        priceView.adapter = priceAdapter

        val distanceView = ListView(context)
        distanceView.dividerHeight = 0
        distanceAdapter =
            ListDropDownAdapter(
                context,
                listOf(*distance)
            )
        distanceView.adapter = distanceAdapter

        val starView: View =
            layoutInflater.inflate(R.layout.custom_layout, null)
        val starItem: GridView = starView.findViewById(R.id.constellation)
        val ok = starView.findViewById<TextView>(R.id.ok)

        starAdapter =
            ConstellationAdapter(
                context,
                stars
            )
        starItem.adapter = starAdapter

        //init popupViews
        popupViews.clear()
        popupViews.add(hallTypeView)
        popupViews.add(priceView)
        popupViews.add(distanceView)
        popupViews.add(starView)

        //add item click event
        hallTypeView.onItemClickListener =
            AdapterView.OnItemClickListener { parent, view, position, id ->
                hallTypeAdapter!!.setCheckItem(position)
                mDropDownMenu!!.setTabText(if (position == 0) headers[0] else hallType[position])
                mDropDownMenu!!.closeMenu()

                //重新加载数据
                cinemaViewModel.loadCinemaDataByHallType(cityCode, hallTypeMap[position]!!,pricePosition,starPosition)
            }

        priceView.onItemClickListener =
            AdapterView.OnItemClickListener { parent, view, position, id ->
                priceAdapter!!.setCheckItem(position)
                mDropDownMenu!!.setTabText(if (position == 0) headers[1] else price[position])
                mDropDownMenu!!.closeMenu()

                when (position) {
                    1 -> {
                        pricePosition = 1
                        cinemaViewModel.getCinemaByCondition(pricePosition, starPosition)
                    }
                    2 -> {
                        pricePosition = 2
                        cinemaViewModel.getCinemaByCondition(pricePosition, starPosition)
                    }
                    else -> {
                    }
                }

            }

        distanceView.onItemClickListener =
            AdapterView.OnItemClickListener { parent, view, position, id ->
                distanceAdapter!!.setCheckItem(position)
                mDropDownMenu!!.setTabText(if (position == 0) headers[2] else distance[position])
                mDropDownMenu!!.closeMenu()
            }

        starItem.onItemClickListener =
            AdapterView.OnItemClickListener { parent, view, position, id ->
                starAdapter!!.setCheckItem(position)
                starPosition = position
            }

        ok.apply {
            setOnClickListener {
                cinemaViewModel.getCinemaByCondition(pricePosition, starPosition)
                mDropDownMenu!!.setTabText(
                    if (starPosition == 0) headers[3] else stars[starPosition]
                )
                mDropDownMenu!!.closeMenu()
            }
        }

        //init context view
        val contentView = TextView(context)
        contentView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            1
        )
//        contentView.text = "内容显示区域"
        contentView.gravity = Gravity.CENTER
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)

        mDropDownMenu!!.setDropDownMenu(
            listOf(*headers),
            popupViews,
            contentView
        )

    }


    override fun onDestroy() {
        super.onDestroy()
        LocationService.destroyLocation()
    }
}


class GlideImageLoader : ImageLoaderInterface<View> {

    override fun createImageView(context: Context?): View {
        return ImageView(context);
    }

    override fun displayImage(context: Context?, path: Any?, imageView: View?) {
        Glide.with(context!!)
            .load(path)
            .placeholder(R.mipmap.logo)
            .error(R.drawable.error)
            .into(imageView as ImageView)
    }
}
